package accs.model.mail.cracker;

import java.io.IOException;
import java.util.ArrayList;

import accs.gui.logic.CheckerTask;
import accs.model.mail.MailCheckResult;
import accs.model.mail.MailChecker;

public class MailCrackerTask extends CheckerTask {

	private boolean running=false;
	private int threadNumber=1;
	private String email;
	private ArrayList<String> passwords;
	private int currentPair=-1;
	
	private int working=0;
	private int notWorking=0;
	
	public MailCrackerTask() {
	}
	
	public void start() {
		if(!running) {
			running=true;
			for(int i=0; i<threadNumber; i++) {
				new Worker().start();
			}
		}
	}

	public void stop() {
		running=false;
	}

	public boolean isRunning() {
		return running;
	}

	public int getTotal() {
		return passwords.size();
	}
	
	private synchronized String giveData() {
		currentPair++;
		if(currentPair<passwords.size()) {
			return passwords.get(currentPair);
		} else {
			return null;
		}
	}
	
	private synchronized void putWorking() throws IOException {
		working++;
		fireProgressUpdate(working, notWorking, passwords.size());
	}
	
	private synchronized void putNotWorking() {
		notWorking++;
		fireProgressUpdate(working, notWorking, passwords.size());
	}
	
	private class Worker extends Thread {
		public void run() {
			MailChecker checker=new MailChecker();
			
			while(running) {
				String pass=giveData();
				if(pass==null) return;
				
				try {
					MailCheckResult res=checker.checkAdress(email, pass);
					
					if(res==MailCheckResult.VALID) {
						putWorking();
						fireInfoTextUpdate("Found: "+email+" - "+pass);
					} else {
						putNotWorking();
					}
					
				} catch (Exception e) {
					System.out.println(e.toString());
					putNotWorking();
				}
				
			}
		}
	}

	public void close() throws IOException {
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setPasswords(ArrayList<String> passwords) {
		this.passwords = passwords;
	}

	public void setThreadNumber(int threadNumber) {
		this.threadNumber = threadNumber;
	}

	public String getTitle() {
		return "MailCracker for "+email;
	}
}